package product

import (
	"errors"
	"mime/multipart"
	"strings"
	"vue-admin-server/model/product"

	"vue-admin-server/global"
	"vue-admin-server/utils/upload"
)

type FileUploadAndDownloadService struct{}

func (e *FileUploadAndDownloadService) Upload(file product.FileUploadAndDownload) error {
	return global.GVA_DB.Create(&file).Error
}

func (e *FileUploadAndDownloadService) UploadFile(header *multipart.FileHeader, noSave string) (err error, file product.FileUploadAndDownload) {
	oss := upload.NewOss()
	filePath, key, uploadErr := oss.UploadFile(header)
	if uploadErr != nil {
		panic(err)
	}
	if noSave == "0" {
		s := strings.Split(header.Filename, ".")
		f := product.FileUploadAndDownload{
			Url:  filePath,
			Name: header.Filename,
			Tag:  s[len(s)-1],
			Key:  key,
		}
		return e.Upload(f), f
	}
	return
}

func (e *FileUploadAndDownloadService) DeleteFile(file product.FileUploadAndDownload) (err error) {
	var fileFromDb product.FileUploadAndDownload
	err, fileFromDb = e.FindFile(file.ID)
	if err != nil {
		return
	}
	oss := upload.NewOss()
	if err = oss.DeleteFile(fileFromDb.Key); err != nil {
		return errors.New("文件删除失败")
	}
	err = global.GVA_DB.Where("id = ?", file.ID).Unscoped().Delete(&file).Error
	return err
}

func (e *FileUploadAndDownloadService) FindFile(id uint) (error, product.FileUploadAndDownload) {
	var file product.FileUploadAndDownload
	err := global.GVA_DB.Where("id = ?", id).First(&file).Error
	return err, file
}
